﻿using UnityEngine;
using System.Collections.Generic;
using System.Reflection;
using System.Linq.Expressions;
using System.Extension;
using System;
[ExecuteInEditMode]
public class ControlBehaviour : MonoBehaviour
{
    [HideInInspector] public Control control;
    [HideInInspector] public List<Command> commands;
    [HideInInspector] public List<Group> groups;

    List<LinkCatch> catchLinks;

    static Stack<ControlBehaviour> m_navigationStack;
    protected static Stack<ControlBehaviour> navigationStack
    {
        get
        {
            if (m_navigationStack == null)   m_navigationStack = new Stack<ControlBehaviour>();
            return m_navigationStack;
        }
    }

    public virtual void OnEnable()
    {
        this.ForEachMemberAttribute<Synchronise>((m, s) => s.Load(this, m));
        if (gameObject.activeSelf)
        {
            catchLinks = control.Sync();
            commands.ForEach(c => c.LinkMethod(this));
            catchLinks.AddRange(Group.GenerateGroups(groups, this));
        }
#if WRB_HIGHSTAKES
       //HighStakesScreen.LocalizeTexts(gameObject);
#endif
    }

    void Start()
    {
 #if WRB_HIGHSTAKES
        //HighStakesScreen.LocalizeTexts(gameObject);
#endif
    }

    public virtual void OnDisable()
    {
       this.ForEachMemberAttribute<Synchronise>((m, s) => s.Catch(this, m));
        commands.ForEach(c => c.Clear());
        Group.ClearGroups(groups);
        catchLinks.Clear();
        catchLinks = null;
    }

    void LateUpdate()
    {
        if(catchLinks.isNotNull())
            catchLinks.ForEach(link => link.Sync());
    }

    public void NavigateTo(object screen)
    {
        if (screen is ControlBehaviour)
        {
            ControlBehaviour nextScreen = screen as ControlBehaviour;
            nextScreen.gameObject.SetActive(true);
            navigationStack.Push(this);
            gameObject.SetActive(false);
        }
    }

    public void NavigateBack()
    {
        if (navigationStack.Count > 0)
        {
            ControlBehaviour previousScreen = navigationStack.Pop();
            previousScreen.gameObject.SetActive(true);
            gameObject.SetActive(false);
        }
    }
}
